jQuery(document)
		.ready(function() {
			//alert("calling ready");
			var showNumberOfCaps=13;
			var itemsPerPage = 100;
			var start = 1;
			var stop = 10;
			var totalSources = 40;
			var path = location.pathname;
			var page = path.substring(path.lastIndexOf("/") + 1,
					path.length);
			
			var root_url ='http://www.dasregistry.org/';//'http://localhost:8000/regrest/';//'http://localhost:8080/regrest/';//'http://www.dasregistry.org/';//'http://dasregistry.sandbox.sanger.ac.uk/';//'http://localhost:8080/regrest/';// 'http://www.dasregistry.org/';// "http://localhost:8080/dasregistry/";//'http://www.dasregistry.org/';//'http://localhost:8080/dasregistry/';//change
			// this to
			// http://www.dasregistry.org/
var server_url = root_url + 'das/sources?';
var base_url = root_url + 'das/sources?';

var parameters = '';// store the parameters from a request to
// cope with authority etc from coordsys
// page links

var sourcesObjects;// instead of making two calls one to find
// the total and one to display we can reuse
// these objects
var caps = new Array();
caps[0] = "sources";
caps[1] = "stylesheet";
caps[2] = "features";
caps[3] = "types";
caps[4] = "sequence";
caps[5] = "entry_points";
caps[6] = "alignment";
caps[7] = "structure";
caps[8] = "interaction";
caps[9] = "bigfile-bam";
caps[10] = "bigfile-bigbed";
caps[11] = "bigfile-bigwig";
caps[12] = "adjacent-feature";
caps[13] = "format";
caps[14] = "unknown-segment";
caps[15] = "unknown-feature";
caps[16] = "error-segment";
caps[17] = "maxbins";
caps[18] = "cors";
caps[19] = "feature-by-id";
caps[20] = "adjacent-feature";


//creat a map for inspecting properties easily for the values we want rather than looping all the time
function createPropertyMap(properties){
	var map=new Object();
	if(properties.length>0 && properties!=null && properties!=undefined){
	for(var propIndex=0;propIndex<properties.length; propIndex++){
	var name=properties[propIndex].name;
	var value=properties[propIndex].value;
	map[name]=value;
	//alert(name +'='+value);
	}
	}
	return map;
}

function getRootURL(queryURI){
	var indexOfLastSlash=queryURI.lastIndexOf("/");
	var rootURL=queryURI.substring(0,indexOfLastSlash);
	var found=0;
	//if queryuri doesn't contain a command just return the queryuri
	for(var i=0;i<caps.length; i++){
		//alert(rootURL.indexOf(caps[i]));
	if(queryURI.indexOf(caps[i])>0){
		found=1;
	}
	
	}
	//if no command found just return the uri don't chop it
	if(found==0){
		return queryURI;
	}
//alert('rootUrl='+rootURL);	
return rootURL;	
}

function getCoordinateUri(coordinateUri){
	var lastSlash=coordinateUri.lastIndexOf("/");
	var uri=coordinateUri.substring(lastSlash+1,coordinateUri.length);
	return uri;
}


function getTestUrl(baseuri, command, testCode) {
	var testurl;
	var extension;
	// alert(baseuri+' ' +command+' '+testCode);
	//should change this to get the test url from the das/sources/dsn/capabilities uri?? will this confuse clients?
	if (command == "sources") {
		testurl = baseuri;
		return testurl;
	}
	
	if (command == "stylesheet") {
		extension = command;
	}
	
	if (command == "features") {
		extension = command + "?segment=" + testCode;
	}
	
	if (command == "types") {
		extension = command;
	}
	
	if (command == "sequence") {
		extension = command + "?segment=" + testCode;
	}
	
	if (command == "entry_points") {
		extension = command;
	}
	
	if (command == "alignment") {
		extension = command + "?query=" + testCode;
	}
	
	if (command == "structure") {
		extension = command + "?query=" + testCode;
	}
	
	if (command == "interaction") {
		extension = command + "?interactor=" + testCode;
	}
	
	if (command == "unknown-segment") {
		extension = "features" + "?segment="
				+ 'invalidTestCode' + ":1,1000";
	}
	
	if (command == "unknown-feature") {
		extension = "features" + "?feature_id="
				+ 'invalidTestCode';
	}
	
	if (command == "error-segment") {
		extension = "features" + "?segment="
				+ 'invalidTestCode' + ":1,1000";
	}
	
	if (command == "maxbins") {
		extension = "features" + "?segment=" + testCode
				+ ";maxbins=1";
	}
	if(command == "feature-by-id"){
		extension = "features" + "?feature_id=";
	}
	if(command == "bigfile-bam"){
		extension == "";
	}
	

	testurl = baseuri +'\/'+extension;

	return testurl;
}

var responseToGetTotal = function(res) {
	//alert('responseToGetTotal'+res.total);
		totalSources = res.total;
		// if total is undefined then no sources returned
		// display this

		// if this is the first call with keyword then we can reuse
		// the object rather than do another request- set up methods
		// to do this
		// , maybe just need an if first flag in write sources
		// method use the sourcesObject then reset to not first so
		// we can make requests thereafter.
		
		if (totalSources == 0) {

			$('#sourcesDiv').html(
					'No sources returned for this query.');
			$('#ajaxLoaderSources').html('');
		} else {
			// var id=res.SOURCE[0].uri;

			$("#Sources-Pagination").pagination(totalSources, {
				items_per_page : itemsPerPage,
				callback : handlePaginationClick,
				link_to : "#Sources-Pagination"
			});
		}

		//alert('total in gettotal='+total+id);

	};

	
	function loadSourcesFirstTime(){
		//alert('first time loader');
			if ($('#ajaxLoaderSources').val() == '') {
				$("#ajaxLoaderSources").html(
						'<img src=\"' + 'img/ajax-loader.gif' + '\">');
			}
			if ($('#ajaxLoaderCoordinates').val() == '') {
				$("#ajaxLoaderCoordinates").html(
						'<img src=\"' + 'img/ajax-loader.gif' + '\">');
			}	
			server_url = base_url + parameters;// '&keywords='+keywords;
			getTotalSources();

		}

		function getTotalSources() {
			//alert("calling get total");
			var d = new Date();
			//start and stop don't effect total so just return 1 source- need to change this so we use same start and stop and then use objects rather than running request again
			JSDAS.sources(escape(server_url + '&rows=' + 1 + '-'
					+ 1 + '&neverused=' + d.getTime()),
					responseToGetTotal, error_response);

			//alert("ending get total");
		}







		function handlePaginationClick(new_page_index,
				pagination_container) {
			// This selects 20 elements from a content array
			if ($('#ajaxLoaderSources').val() == '') {
				$("#ajaxLoaderSources").html(
						'<img src=\"' + 'img/ajax-loader.gif' + '\">');
			}
			loadSources(new_page_index);
			//alert('just done loadSources');
		}

		function loadSources(new_page_index) {
			//alert(new_page_index);
			start = (new_page_index * itemsPerPage) + 1;
			stop = start + itemsPerPage - 1;
			var d = new Date();

			JSDAS.sources(escape(server_url + '&rows=' + start + '-'
					+ stop + '&neverused=' + d.getTime()), response,
					error_response);
			$.ajaxSetup( {
				cache : false
			});
		}

	
/**
 * This function print the Sources uri and title
 */
var response = function(res, divId) {
	//alert('calling response method');
	// var total=res.total;
	// text+="total="+total;
	// text = '<link rel=\"stylesheet\" type=\"text/css\"
	// href=\"stylesheet.css\" />';
	text = '';// reset the data	
	text += '<div id=\"table\"><table id=\"list\"class=\"dastable\">';
	// get info on sources size from sources attr
	totalSources = res.total;

	// print headers

	text += '<tr class="row0">';

	text += '<td><b>pos</pos></td>';
	text += '<td><b>ID<b><a href="listSources.jsp?sort=id"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=id;reverse=true"><img src="img/down_sort.gif"/></a></td>';

	// text +='<td><b>clients</b></td>';

	text += '<td><b>';
	text += 'Title';

	text += '</b><a href="listSources.jsp?sort=title"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=title;reverse=true"><img src="img/down_sort.gif"/></a></td>';
	text+='<td><b>Status</b><a href="listSources.jsp?sort=status"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=status;reverse=true"><img src="img/down_sort.gif"/></a></td>';

	// text +='<td><b>';
	// text += 'status';
	// text +='</b></td>';

	text += '<td><b>';
	text += 'Description';
	text += '</b><a href="listSources.jsp?sort=description"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=description;reverse=true"><img src="img/down_sort.gif"/></a></td>';
	var checked='';
	if(showNumberOfCaps==caps.length){
		checked='checked=\"no\"';
	}
	text += '<td colspan=\'' + showNumberOfCaps + '\'><b>Capabilities<b><a href="listSources.jsp?sort=validcapabilities"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=validcapabilities;reverse=true"><img src="img/down_sort.gif"/></a>';
	text+='<input type=\"checkbox\" id=\"showAllCaps\" name=\"showAllCaps\" '+checked+' />show all caps</td>';

	text += '<td><b>Types';
	text += '</b></td>';

	text += '<td>Specification</td>';
	text += '<td>Project</td>';
	text += '<td><b>';
	text += 'Registered';
	text += '</b><a href="listSources.jsp?sort=registerdate"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=registerdate;reverse=true"><img src="img/down_sort.gif"/></a></td>';
	text += '<td>Coordinate System<a href="listSources.jsp?sort=coordinatesystem"><img src="img/up_sort.gif"/></a><a href="listSources.jsp?sort=coordinatesystem;reverse=true"><img src="img/down_sort.gif"/></a></td>';
	text += '</tr>';

	var row = 'row0';
	if(res.SOURCE==undefined || res.SOURCE.length==0){
		$("#ajaxLoaderSources").html('');
		return text="No sources returned for this query";
	}else{
	for ( var i = 0; i < res.SOURCE.length; i++) {

		// need to find the number of coordinate systems for
		// this source to see how many rowspans tds need to be

		var coordinates = res.SOURCE[i].VERSION[0].COORDINATES;
		var rowspan = 1;
		if (coordinates) {
			var numberOfCoords = coordinates.length;
			//alert('number of coords'+ numberOfCoords);
			
			if (numberOfCoords) {
				rowspan = numberOfCoords;
			}
		}
		//alert('just got coords');
		var propMap=createPropertyMap(res.SOURCE[i].VERSION[0].PROP);
		
		//get the number of days before deletion if specified
		//if not then valid else invalid
		var daysBeforeDeletion=60;
		if(propMap['daysBeforeDeletion']){
		daysBeforeDeletion=propMap['daysBeforeDeletion'];	
		//alert(daysBeforeDeletion);
		}
		
		var versionUri=res.SOURCE[i].VERSION[0].uri;
		var registeredDate=res.SOURCE[i].VERSION[0].created
		var sourceId=res.SOURCE[i].uri;
		// alert('number of coords='+numberOfCoords);

		for ( var l = 0; l < rowspan; l++) {

			if (i % 2 == 0) {
				row = 'row1';
			} else {
				row = 'row0';
			}
			text += '<tr class=\"' + row + '\">';
			var position = start + i;
			if (l == 0) {// only do this loop once for a
							// source
				//alert('in l=1');
				text += '<td rowspan=\'' + rowspan + '\'>'
						+ position + '</td>';
				text += '<td rowspan=\'' + rowspan + '\'>'
						+ res.SOURCE[i].uri;
				
				text+='<div id=\"dassourceactions\" title=\"show details\"><a href=\'showdetails.jsp?auto_id='+sourceId+'\'>';
					text+='<img src=\"img/messagebox_info16x16.png\" border=\"0\"/></a></div>';	
					text+='<div id=\"dassourceactions\" title=\"validate\"><a href=\'validateServer.jsp?auto_id='+sourceId+'\'>';
					text+='<img src=\"img/ok16x16.png\" border=\"0\"/></a></div>';
					
					text+='<div id=\"dassourceactions\" title=\"send to freind\"><a href=\'sendToFriend.jsp?auto_id='+sourceId+'\'>';
					text+='<img src=\"img/mail_post_to16x16.png\" border=\"0\"/></a></div>';	
					
//			<div id="dassourceactions" title="header=[validate] body=[validate the <%=ds.getNickname()%> server]"><a href="validateServer.jsp?auto_id=<%=ds.getId()%>"> 
//				<img 	src="img/ok16x16.png" border="0" alt="validate"
//				onMouseOver="window.status='validate'; return true;"
//				onMouseOut="window.status=' '; return true;"></a>
//				</div>
//			<div id="dassourceactions" title="header=[send to friend] body=[notify a friend about the <%=ds.getNickname()%> server]">
//				<a href="sendToFriend.jsp?auto_id=<%=ds.getId()%>"> 
//				<img src="img/mail_post_to16x16.png" boder="0" alt="edit"
//				onMouseOver="window.status='send to friend'; return true;"
//				onMouseOut="window.status=' '; return true;"></a>
//				</div>
				
				
				
				
						text+= '</td><td rowspan=\'' + rowspan
						+ '\'>' + res.SOURCE[i].title
						+ '</td>'+
						'<td rowspan=\'' + rowspan
						+ '\'>';
				if(daysBeforeDeletion!=60){
					text+='<a href=\"http://www.dasregistry.org/validateServer.jsp?auto_id='+sourceId+'\" title=\''+daysBeforeDeletion+' days before deletion\'><img src=\"img/messagebox_warning.png\"/>Source down/invalid removal in '+daysBeforeDeletion+' days.</a></td>';
				}
				text+='</td>'+
						'<td rowspan=\'' + rowspan
						+ '\'>'+'<a class=\"clickDescription\"  >Show/Hide</a>'
						+'<div class=\'shortdescription\'>'
						+ '<a href=\"'+res.SOURCE[i].doc_href+'\">Further Information</a> '
						+ res.SOURCE[i].description;
				//	+ res.SOURCE[i].description.substring(0,60)+'...';
						+ '</div></td>';
				

						var shortQueryUri=getRootURL(res.SOURCE[i].VERSION[0].CAPABILITY[0].query_uri);
						//alert('shortQueryUri');
						
				for (k = 0; k < showNumberOfCaps; k++) {
					text += '<td rowspan=\'' + rowspan + '\' class=\'noBorder\'>';
					var cap = caps[k];
					// text+=cap;
					var image = '<img class="valid" src=\"' + 'img/clear16.gif' + '\">';// default
					// color
					// for
					// img
					

						var status = propMap[cap];
						var img = '';

						if ('valid' == status)
							img = 'img/green16.gif';
						if ('probably_valid' == status)
							img = 'img/amber16.gif';
						if ('invalid' == status)
							img = 'img/red16.gif';
						if (img == '')
							img = 'img/clear16.gif';

						
						var test_range='';
						if(coordinates){
						test_range=coordinates[0].test_range;
						}
						
						//chop off the command from the quer_uri oin future will need to get the specific uri as these will be allowed to be different
						
						//alert(shortQueryUri);
//						var shortQueryUri=query_uri.replace(cap, "");
//						if((i==0)&&(k==0)){
//							alert(query_uri);
//						alert(shortQueryUri);	
//						}
						text += '<a title=\''+cap+' capability is '+status+'\' href=\"' + getTestUrl(
									shortQueryUri,
									cap,
									test_range) + '\">';
							image = '<img class="valid" src=\"' + img + '\"><\/>';
							
						

					
					text += image + '</td>';

				}
				
				text += '<td rowspan=\'' + rowspan + '\'>';
				
				var idForTypes='no types';
					if(propMap['types']=='valid'){idForTypes=versionUri;//ideally should be just source uri =auto_id but because of mirrored sources need url
					text += '<a class=\"click\"  >Show/Hide Types</a>';
					}
				text += '<div class=\"ajaxTypes\" id=\"' + idForTypes + '\"></div>';
				text += '</td>';// <a
								// class="click">Expand/Contract</a>
				// <div class="ajaxTypes" id="<%=auto_id
				// %>"></div>
				text += '<td rowspan=\'' + rowspan + '\'>'+propMap['spec']+'</td>';
				var projectIcon=propMap['projectIcon'];
				if(projectIcon!=undefined){
				var projectId=projectIcon.substring(projectIcon.indexOf('=')+1);
				
				text += '<td rowspan=\'' + rowspan + '\'><a href=\'http://www.dasregistry.org/showProjectDetails.jsp?project_id='+projectId+'\'\'>'+'<img src=\''+projectIcon+'\'></a></td>';
				}else{
				text+=	'<td rowspan=\'' + rowspan + '\'></td>';
				}
				text += '<td rowspan=\'' + rowspan + '\'>'+registeredDate.toDateString()+'</td>';
				}// end of l==0 loop for listing source once as
				// span should take care of filling in the rows
				// below.
			// alert('coordinates length='+coordinates.length);

			if (coordinates == undefined || coordinates == null) {// fill
																	// with
																	// empty
																	// tds
																	// though
																	// technically
																	// why
																	// sources
																	// have
																	// no
																	// coords
																	// is
																	// bad
																	// and
																	// should
																	// be
																	// corrected
																	// -
																	// happening
																	// with
																	// mirrored
																	// sources
																	// only
				text += '<td >' + '</td>' + '<td >' + '</td>'
						+ '<td >'

						+ '</td>' + '<td >'

						+ '</td>' + '<td >'

						+ '</td>';
			} else {

				text += '<td >' + '<a href=\''
						+ coordinates[l].uri + '\'>'
						+ coordinates[l].textContent + '</a>'
						+ '<br/><a href=\''
						+ 'listSources.jsp?coordinateid='+getCoordinateUri(coordinates[l].uri) + '\'>'
						+ ' List Sources' + '</a>'
						+ '</td>';

			}

			text += '</tr>';
		}
		;
	}
	}
	text += '</table></div>';
	$("#sourcesDiv").html(text);// need to set html here as the
								// response from server may take
								// a while
	// $('#sourcesDiv a').click(function(){alert('click now
	// works')});
//	
	$(".click").click(function() {

		$(this).next().toggleClass("ajaxTypesLarge");
		var id = $(this).next().attr("id");
		// alert("id="+id);
			if ((id != undefined) && (id != "")) {
				$(this).next().load("types.jsp" + "?id=" + id);
		}
			});
	
	$(".clickDescription").click(function() {
		$(this).next().toggleClass("longdescription");
		
			});
	
	$("#showAllCaps").click(function() {
		//alert('clicked');
		if(showNumberOfCaps==13){
		showNumberOfCaps=caps.length;
	}else{
		showNumberOfCaps=13;
	}
		$("#ajaxLoaderSources").html(
				'<img src=\"' + 'img/ajax-loader.gif' + '\">');
		var d = new Date();
		//start and stop don't effect total so just return 1 source- need to change this so we use same start and stop and then use objects rather than running request again
		JSDAS.sources(escape(server_url + '&rows=' + start + '-'
				+ stop + '&neverused=' + d.getTime()),
				response, error_response);
			});
	
	
	
//	$(".shortdescription").hover(function (){
//		$(this).toggleClass("longdescription")
//	
//	});
	// $('a img').tooltip();
	$("#ajaxLoaderSources").html('');
	$('#totalSourcesDiv').html(
			start + '-' + stop + ' of ' + totalSources);
	//alert('returning text'+text);
	return text;
};


/**
 * This function will be executed in case of error
 */
var error_response = function() {
	//alert('Bad response, Wrong URL?, No Sequence XML?');
	text='<font color=\"red\">The search service is down please use the search functionality at <a href="listServices.jsp\">List Sources</a> instead</font>';
	$("#sourcesDiv").html(text);
	$("#coordinatesDiv").html(text);
	$("#ajaxLoaderSources").html('');
	$("#ajaxLoaderCoordinates").html('');
	
};

$(function() {

					var paramString = location.search;
					// alert('calling blank function for page');
					if (page == "listSources.jsp") {// only send request to
														// registry if request
														// is for the search
														// page
						// alert('location='+location);
						// alert('path='+path);
						parameters = paramString.substring(1);// set the
																// params so if
																// a page
																// request we
																// can get the
																// right data
																// and cho
						// alert('paramString='+paramString);
						var value = $(document).getUrlParam("keywords");
						// if(value==''){
						// parameters=parameters.replace('keywords=', ''); //if
						// no keywords specified get rid of the parameter so all
						// results returned
						// }
						// alert("nav sources"+value);
						// if ( value){//only submit if a keyword has been put
						// in and search pressed
						$('#keywords').val(value);// set the value in diplay
													// for the current page as
													// could have come from
													// another page
						loadSourcesFirstTime();
					}
					// $('#menu ul li a[href$="' + path + '"]').attr('class',
					// 'active');
				});




});